<template>
  <el-select
    v-select-scroll
    v-model="computedValue"
    :multiple="multiple"
    :filter-method="filterData"
    :placeholder="placeholder"
    value-key="id"
    filterable
    clearable
    size="small"
    class="width240"
  >
    <template v-if="defaultValue" >
      <Options v-for="item in defaultValue" :item="item" :key="'hide'+item.id" class="hide" />
    </template>
    <Options v-for="user in userList" :item="user" :key="user.id" />
  </el-select>
</template>

<script>
import { getUserList } from '@/api/user';
import Options from './options';

export default {
  components: { Options },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: Array | String,
      default: ''
    },
    defaultValue: {
      type: Array | String,
      default: () => ([])
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  data() {
    return {
      userList: []
    };
  },
  computed: {
    computedValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('change', val);
      }
    }
  },
  created() {
    this.getUser();
  },
  methods: {
    filterData(name) {
      this.getUser(name);
    },
    getUser(userName = '') {
      const params = {
        page: 1, perPage: 20
      };
      if (userName) params.userName = userName;
      getUserList(params).then(res => {
        if (res.code === 200) {
          this.userList = res.data.items;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.hide {
  display: none;
}
</style>
